﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketChat.Common;
using WebSocketChat.Common.Server;
using Newtonsoft.Json;
using WebSocketChat.Common.Database;
using CCWin.SkinControl;
using System.Collections.Concurrent;
using SuperSocket.WebSocket;

namespace WebSocketChat.Services
{
    public class ServiceMain
    {
        private SServerWebSocket _serverWeb;
        private ServerSocket _server;
        private Helper dbHelper;

        public void Start()
        {
            if (_serverWeb != null)
                _serverWeb.Stop();
            _serverWeb = new SServerWebSocket();
            _serverWeb.Start();
            if (dbHelper == null)
                dbHelper = new Helper();

            if (_server != null)
                _server.Close();
            _server = new ServerSocket();
            _server.MessageArrive += Socket_MessageArrive;
            _server.Create();
            _server.Accept();
        }

        private void Socket_MessageArrive(MessageArriveEventArgs obj)
        {
            var msg = obj.Message;
            if (msg == null)
                return;
            switch (msg.Type)
            {
                case MessageType.Online:
                    var user = JsonConvert.DeserializeObject<ChatUser>(msg.Data.ToString());
                    ServerSocket.Users.TryAdd(obj.Current.RemoteEndPoint.ToString(), new SocketUser()
                    {
                        Socket = obj.Current,
                        User = user
                    });
                    //广播上线信息
                    IMessage info = new CommandMessage()
                    {
                        Data = user,
                        Type = MessageType.Online
                    };
                    Console.WriteLine(user.LoginID + " Login");
                    dbHelper.ChangeUserState(user.ID, ChatListSubItem.UserStatus.Online);
                    _server.BroadcastFriend(user.ID, info);
                    break;
                case MessageType.Friend:
                    var user1 = JsonConvert.DeserializeObject<ChatUser>(msg.Data.ToString());
                    IMessage groupmsg = new CommandMessage()
                    {
                        Data = dbHelper.GetChatGroups(user1.ID),
                        Receiver = user1.ID,
                        Type = MessageType.Friend,
                    };
                    obj.Current.Send(groupmsg.Serialize());
                    break;
                case MessageType.Offline:
                    var user2 = msg.Data as ChatUser;
                    if (user2 == null)
                        user2 = JsonConvert.DeserializeObject<ChatUser>(msg.Data.ToString());
                    //广播下线信息
                    IMessage info1 = new CommandMessage()
                    {
                        Data = user2,
                        Type = MessageType.Offline
                    };
                    Console.WriteLine(user2.LoginID + " Logout");
                    dbHelper.ChangeUserState(user2.ID, ChatListSubItem.UserStatus.OffLine);
                    _server.BroadcastFriend(user2.ID, info1);
                    break;
                case MessageType.Chat:
                    //var chatmsg = msg.Data as ChatBoxContent;
                    if (!_server.Transport(msg))
                    {
                        foreach (var item in SServerWebSocket.Clients)
                        {
                            if (msg.Receiver == item.Value.User.ID)
                            {
                                var chatmsg = msg as ChatMessage;
                                if (chatmsg != null)
                                {
                                    var content = chatmsg.Data as CCWin.SkinControl.ChatBoxContent;
                                    var finaltext = content.Text;
                                    if (content.EmotionDictionary.Count > 0)
                                    {
                                        foreach (var emot in content.EmotionDictionary)
                                        {
                                            finaltext = finaltext.Insert((int)emot.Key, "face" + Common.Client.Emotion.Emotions[emot.Value]);
                                        }
                                    }
                                    var fromuser = dbHelper.GetUser(msg.Sender);
                                    chatmsg.Data = new Common.Client.MessageItem()
                                    {
                                        username = fromuser.NickName,
                                        avatar = "../Images/" + fromuser.HeadPortrait,
                                        id = fromuser.ID,
                                        type = msg.Type == MessageType.Chat ? "friend" : "group",
                                        content = finaltext,
                                        cid = 0,
                                        fromid = msg.Sender,
                                        mine = false
                                    };
                                    item.Value.Session.Send(msg.ChangeMsg().SerializeJson());
                                }
                            }
                        }
                    }
                    break;
                case MessageType.GroupChat:
                    break;
                default: break;
            }
        }

        public void Stop()
        {
            if (_serverWeb != null)
                _serverWeb.Stop();
            if (_server != null)
                _server.Close();
        }
    }
}
